﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

namespace Abc.Utils;
/// <summary>
/// laui treetable 扩展
/// </summary>
public static class LayuiTreeTableExtension
{
    /// <summary>
    /// 获取layui treetable
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="datas">list集合</param>
    /// <param name="pKey">父级</param>
    /// <returns></returns>
    public static LayuiPagedList<TEntity> ToLayuiTreeTableList<TEntity>(this List<TEntity> datas, string pKey = "") where TEntity : ILayuiTreeTable<TEntity>
    {

        var pageList = new LayuiPagedList<TEntity>();
        pageList.data = GetChildren<TEntity>(datas, pKey);
        pageList.count = datas.Count;
        pageList.totalpage = 1;
        pageList.page = 1;
        pageList.limit = datas.Count;
        return pageList;
    }

    /// <summary>
    /// 获取layui treetable
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="pageList"></param>
    /// <param name="pKey">父级</param>
    /// <returns></returns>
    public static LayuiPagedList<TEntity> ToLayuiTreeTableList<TEntity>(this LayuiPagedList<TEntity> pageList, string pKey = "") where TEntity : ILayuiTreeTable<TEntity>
    {
        pageList.data = GetChildren<TEntity>(pageList.data, pKey);

        return pageList;
    }

    /// <summary>
    /// 递归获取 Children
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="menus"></param>
    /// <param name="pKey"></param>
    /// <returns></returns>
    private static List<TEntity> GetChildren<TEntity>(IEnumerable<TEntity> menus, string pKey = "") where TEntity : ILayuiTreeTable<TEntity>
    {

        List<TEntity> menuItems = new List<TEntity>();
        foreach (var menuitem in menus.Where(o => o.PKey != null && o.PKey.ToLower() == pKey.ToLower()).OrderBy(o => o.Sort))
        {
            if (!string.IsNullOrWhiteSpace(menuitem.Key) && menus.Any(o => o.PKey != null && o.PKey.ToLower() == pKey.ToLower()))
            {
                menuitem.children = GetChildren(menus, menuitem.Key);
            }
            menuitem.IsParent = !string.IsNullOrWhiteSpace(pKey);
            menuItems.Add(menuitem);
        }

        return menuItems;
    }


}
